package ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import service.IBookService;
import service.ICartLineService;
import service.ICartService;
import service.Impl.IBookServiceImpl;
import service.Impl.ICartLineServiceImpl;
import service.Impl.ICartServiceImpl;
import vo.Book;
import vo.Cart;
import vo.CartLine;
import vo.Client;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/*
 * @description: 较少购物车，实现用户点击商品去除商品功能
 * 从前端接收：bookId  从session获得：userId
 */
@WebServlet(name = "CartLineCutServlet")
public class CartLineCutServlet extends HttpServlet {
    private ICartService cartService = new ICartServiceImpl();
    private ICartLineService cartLineService = new ICartLineServiceImpl();
    private IBookService bookService = new IBookServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取输入流
        ServletInputStream inputStream = req.getInputStream();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder=new StringBuilder();
        String temp="";
        while((temp=bufferedReader.readLine())!=null){
            stringBuilder.append(temp);
        }
        //处理成json对象
        String jsonString=stringBuilder.toString();
        JSONObject jsonObject=JSON.parseObject(jsonString);
        //解析json对象
        int cartLineId=Integer.parseInt(jsonObject.getString("cartlineId"));
        cartLineService.delCartLineById(cartLineId);

        //更新session中cart和cartLine
        HttpSession httpSession = req.getSession();
        Client client=(Client) httpSession.getAttribute("client");
        Cart cart= cartService.selectCart(client.getId());
        System.out.println(cart.getTotalPrice());
        List<CartLine> cartLineList = cartLineService.selectCartLineByCartId(cart.getId());
        List<Book> bookList = new ArrayList<>();
        for(CartLine cartLine : cartLineList){
            bookList.add(bookService.selectBookById(cartLine.getBookId()));
        }
        httpSession.setAttribute("cart", cart);
        httpSession.setAttribute("cartLines", cartLineList);
        httpSession.setAttribute("books", bookList);

    }
}
